package com.xqboss.apps.service.consumer;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xqboss.apps.domain.consumer.ConsumerFriends;
import com.xqboss.apps.dto.consumer.ConsumerFriendDto;
import com.xqboss.apps.mapper.consumer.ConsumerFriendsMapper;
import com.xqboss.apps.vo.consumer.ConsumerFriendsVo;
import com.xqboss.common.core.domain.R;
import com.xqboss.common.core.domain.entity.SysDictData;
import com.xqboss.common.core.domain.entity.SysUser;
import com.xqboss.system.mapper.SysUserMapper;
import com.xqboss.system.service.ISysDictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 好友关系Service业务层处理
 *
 * @author xqboss
 * @date 2023-08-15
 */
@Service
public class ConsumerFriendsService extends ServiceImpl<ConsumerFriendsMapper, ConsumerFriends> {
    @Resource
    private ConsumerFriendsMapper consumerFriendsMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Autowired
    private ISysDictTypeService dictTypeService;


    public List<ConsumerFriendsVo> friendsList(ConsumerFriendDto dto) {
        return consumerFriendsMapper.friendsList(dto);
    }

    public R<ConsumerFriendsVo> addSearch(String keyword, Long userId) {
        SysUser user = sysUserMapper.selectUserByUserNameOrId(keyword);
        if (ObjUtil.isNull(user) || user.getHidden()) {
            return R.fail("没有找到该用户");
        }
        List<SysDictData> dictData = dictTypeService.selectDictDataByType("sys_interior_user");
        if (CollUtil.isNotEmpty(dictData)) {
            List<String> list = dictData.stream().map(SysDictData::getDictValue).collect(Collectors.toList());
            if (list.contains(user.getUserName())) {
                return R.fail("没有找到该用户");
            }
        }
        ConsumerFriendsVo friendsVo = BeanUtil.copyProperties(user, ConsumerFriendsVo.class);

        LambdaQueryWrapper<ConsumerFriends> wq = new LambdaQueryWrapper<>();
        wq.eq(ConsumerFriends::getUserId, userId);
        List<ConsumerFriends> myFriendList = consumerFriendsMapper.selectList(wq);
        List<Long> collect = myFriendList.stream().map(ConsumerFriends::getFriendUserId).collect(Collectors.toList());
        if (CollUtil.contains(collect, user.getUserId())) {
            friendsVo.setIsAdd(1);
        }
        return R.ok(friendsVo);
    }

    public List<ConsumerFriendsVo> friendsListMe(ConsumerFriendDto dto) {
        return consumerFriendsMapper.friendsListMe(dto);
    }

}
